package com.onlyxiahui.framework.json.validator.impl;

import java.math.BigDecimal;

import com.alibaba.fastjson.JSONObject;
import com.onlyxiahui.framework.json.validator.Validator;
import com.onlyxiahui.framework.json.validator.ValidatorContext;
import com.onlyxiahui.framework.json.validator.ValidatorData;
import com.onlyxiahui.framework.json.validator.ValidatorResult;
import com.onlyxiahui.framework.json.validator.error.ErrorInfoEnum;
import com.onlyxiahui.framework.json.validator.util.RegexValidatorUtil;

/**
 * 
 * Date 2018-12-26 16:52:03<br>
 * Description
 * 
 * @author XiaHui<br>
 * @since 1.0.0
 */
public class JsonMinValidator implements Validator<JSONObject, Object> {

	@Override
	public String getKey() {
		return "min";
	}

	@Override
	public boolean check(Object judge) {
		return true;
	}

	@Override
	public ValidatorResult valid(ValidatorContext validatorContext, ValidatorData<JSONObject, Object> vd) {
		// JSONObject data = vd.getData();
		Object attribute = vd.getAttribute();
		Object judge = vd.getJudge();
		String code = vd.getCode();
		String message = vd.getMessage();

		ValidatorResult vr = null;
		boolean mark = true;
		BigDecimal minBigDecimal = null;
		if (null != attribute && null != judge) {

			String valueText = attribute.toString();
			String judgeText = judge.toString();

			boolean isValueNumber = RegexValidatorUtil.isNumber(valueText);
			boolean isJudgeNumber = RegexValidatorUtil.isNumber(judgeText);

			if (isValueNumber && isJudgeNumber) {
				BigDecimal bigDecimal = new BigDecimal(valueText);
				minBigDecimal = new BigDecimal(judgeText);
				mark = (minBigDecimal.compareTo(bigDecimal) <= 0);
			}
		}
		if (!mark) {
			vr = new ValidatorResult();
			vr.setErrorCode(code == null ? this.getCode() : code);
			vr.setMessage(message == null ? this.getMessage(minBigDecimal) : message);
			vr.setExtend(vd.getExtend());
		}
		return vr;
	}

	public String getMessage(BigDecimal minBigDecimal) {
		StringBuilder message = new StringBuilder("不能小于");
		if (null != minBigDecimal) {
			message.append(minBigDecimal.toString());
		}
		message.append("！");
		return message.toString();
	}

	public String getCode() {
		return ErrorInfoEnum.RANGE_ERROR.code();
	}
}
